from PySide6 import QtWidgets, QtGui
from application import Application
from functools import partial
import sys
import androiddevicemanager
import autoflow
import autoflow.flowmanager
import scrcpy
import scrcpy.scrcpymanager
import webapi
import labelmanager
import mainwindow

g_DefaultDevice = "16736(翣)"

def updateDeviceScreen():
    frame = Application.instance().getThread("scrcpy").getFrame()
    if frame is not None:
        img = QtGui.QImage(
                frame,
                frame.shape[1],
                frame.shape[0],
                frame.shape[1] * 3,
                QtGui.QImage.Format_BGR888,
            )
        Application.instance().updateScreen(img)

def qProcessEvents():
    QtWidgets.QApplication.instance().processEvents()
    Application.instance().startTimer(0.001, qProcessEvents)
    updateDeviceScreen()

def onDeviceStarted(devicename):
    DebugPrint("device started.")
    serial = Application.instance().getThread("DeviceManager").getDeviceSerial(devicename)
    Application.instance().getThread("scrcpy").connect(serial)

def onAppInitFinished():
    mumudevicename = Application.instance().getCmdArgs("mumudevice", g_DefaultDevice)
    if mumudevicename:
        Application.instance().pushMessage("DeviceManager"
                                           , "StartDevice"
                                           , mumudevicename
                                           , partial(onDeviceStarted, mumudevicename))

def Main():
    QtWidgets.QApplication(sys.argv[:])
    labelmanager.LabelManager()
    app = Application()
    app.parserArgument("d:", ["disableweb=", "ll="])
    webport = app.getConfig("web.port", 8000)
    app.registerInitCallback(onAppInitFinished)

    app.startTimer(1, qProcessEvents)

    app.createThread("DeviceManager", androiddevicemanager.AndroidDeviceManager())
    app.createThread("scrcpy", scrcpy.scrcpymanager.ScrcpyManager())
    #app.createThread("FlowManager", autoflow.flowmanager.FlowManager())
    if not app.getCmdArgs("--disableweb", True):
        app.createThread("WebAPI", webapi.WebApiManager(webport))

    m = mainwindow.MainWindow()
    m.resize(1452,803)
    m.onStarted()
    m.show()
    m.OpenProject("labels_1280_780.json")

    r = app.exec()
    return r

if "__main__" == __name__:
    Main()
